<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" label-width="80px" :inline="true">
        <el-form-item label="工单编号:">
          <el-input v-model="search.taskCode" clearable placeholder="请输入" size="medium" />
        </el-form-item>
        <el-form-item label="工单状态:">
          <el-select v-model="search.status" clearable placeholder="请选择" size="medium">
            <el-option
              v-for="item in taskStatus"
              :key="item.statusId"
              :label="item.statusName"
              :value="item.statusId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="medium"
            class="my-primary1"
            icon="el-icon-search"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-row type="flex" class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="showAdd"
        >新建</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="taskCode" label="工单编号" />
        <el-table-column prop="innerCode" label="设备编号" />
        <el-table-column prop="taskType.typeName" label="工单类型" />
        <el-table-column prop="createType" label="工单方式" />
        <el-table-column
          prop="taskStatusTypeEntity.statusName"
          label="工单状态"
        />
        <el-table-column prop="userName" label="运维人员" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column label="操作" width="120">
          <template v-slot="{ row }">
            <el-button type="text" class="el-button--primary-text" @click.native="showTaskInfo(row.taskId)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          @current-change="taskSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增工单"
      :visible.sync="addDialog"
      width="630px"
      top="15vh"
      @close="addClose"
    >
      <el-form
        ref="add"
        :model="addForm"
        :rules="addRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="设备编号：" prop="innerCode">
          <el-input
            v-model="addForm.innerCode"
            autocomplete="off"
            placeholder="请输入"
            style="width: 396px"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="工单类型：" prop="productType">
          <el-select
            v-model="addForm.productType"
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in taskTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运维人员：" prop="assignorId">
          <el-select
            v-model="addForm.assignorId"
            placeholder="请选择"
            style="width: 396px"
          >
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="desc">
          <el-input
            v-model="addForm.desc"
            type="textarea"
            :rows="4"
            placeholder="请输入备注（不超过40字）"
            style="width: 396px"
            maxlength="40"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button class="my-secondary" @click="addClose">取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="addSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="工单详情"
      :visible.sync="taskInfoDialog"
      width="630px"
      @close="taskInfoClose"
    >
      <div v-if="taskInfo.taskStatus === 3" class="task-status">
        <img
          src=""
          class="icon"
        ><span class="status">取消</span><img
          src="http://likede2-admin.itheima.net/img/pic_3.e8208e34.png"
          class="pic"
        >
      </div>
      <div v-if="taskInfo.taskStatus === 1" class="task-status">
        <img
          src=""
          class="icon"
        ><span class="status">待办</span><img src="http://likede2-admin.itheima.net/img/pic_1.834b274c.png" class="pic">
      </div>
      <el-form label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编号：" prop="innerCode">
              {{ taskInfo.innerCode }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建日期：">
              {{ formattedDate(taskInfo.createTime) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="taskInfo.taskStatus === 3" label="取消日期：">
              {{ formattedDate(taskInfo.updateTime) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运维人员：">
              {{ taskInfo.userName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型：">
              {{ taskInfo.taskType?.typeName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单方式：">
              {{ taskInfo.createType ? "手动" : "自动" }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="taskInfo.taskStatus !== 3" label="备注：">
              {{ taskInfo.desc }}
            </el-form-item>
          </el-col>
          <el-col v-if="taskInfo.taskStatus === 3" :span="12">
            <el-form-item label="取消原因：">
              {{ taskInfo.desc }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button
            v-if="taskInfo.taskStatus === 3"
            class="my-secondary"
            @click="recreate"
          >重新创建</el-button>
          <el-button
            v-else
            class="my-secondary"
            @click="cancelTask(taskInfo.taskId)"
          >取消工单</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTaskStatus,
  taskSearch,
  getTaskTypeList,
  createTask,
  getTaskInfo,
  cancelTask
} from '@/api/task'
import { searchUser } from '@/api/user'
import store from '@/store'
export default {
  data() {
    return {
      search: {
        taskCode: '',
        status: '',
        pageIndex: 1,
        pageSize: 10,
        isRepair: true
      },
      taskStatus: [],
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      addDialog: false,
      taskTypeList: [],
      addForm: {
        createType: 1,
        assignorId: '',
        innerCode: '',
        userId: store.getters.userId,
        productType: '',
        desc: ''
      },
      addRules: {
        innerCode: [{ required: true, message: '请输入', trigger: 'change' }],
        assignorId: [{ required: true, message: '请选择', trigger: 'change' }],
        productType: [{ required: true, message: '请选择', trigger: 'change' }],
        desc: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      detailForm: {},
      channelList: [],
      users: [],
      taskInfoDialog: false,
      taskInfo: {},
      taskDetail: []
    }
  },
  async created() {
    this.taskStatus = await getTaskStatus()
    await this.taskSearch()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.taskSearch()
    },
    async taskSearch() {
      const { currentPageRecords, totalCount, totalPage } = await taskSearch({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = totalPage
      this.tableData = currentPageRecords.map((item) => {
        item.createType = item.createType ? '手动' : '自动'
        item.createTime = this.formattedDate(item.createTime)
        return item
      })
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showAdd() {
      this.addDialog = true
      const list = await getTaskTypeList()
      this.taskTypeList = list.filter((item) => item.type === 1)
      const res = await searchUser({ isRepair: true })
      this.users = res.currentPageRecords
    },
    addClose() {
      this.addDialog = false
      this.$refs.add.resetFields()
      this.addForm = {
        createType: 1,
        assignorId: '',
        innerCode: '',
        userId: store.getters.userId,
        productType: '',
        desc: ''
      }
    },
    async addSubmit() {
      this.$refs.add.validate(async(isOK) => {
        if (isOK) {
          await createTask({ ...this.addForm })
          this.addClose()
          this.taskSearch()
        }
      })
    },
    async showTaskInfo(id) {
      this.taskInfoDialog = true
      this.taskInfo = await getTaskInfo(id)
    },
    taskInfoClose() {
      this.taskInfoDialog = false
    },
    cancelTask(taskId) {
      this.$confirm('取消工单后，将不能恢复，是否确认取消？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        await cancelTask({ taskId, desc: '' })
        this.taskInfoDialog = false
        this.taskSearch()
      })
    },
    async recreate() {
      this.showAdd()
      this.addForm = {
        createType: this.taskInfo.createType,
        assignorId: this.taskInfo.assignorId,
        innerCode: this.taskInfo.innerCode,
        userId: this.taskInfo.userId,
        productType: this.taskInfo.productTypeId,
        desc: this.taskInfo.desc
      }
      this.taskInfoClose()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss'
</style>
